﻿using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace WowDotNetAPI.Utilities
{
    public static partial class JsonUtility
    {
#if SILVERLIGHT
        public static void GetJSON(string url, Action<string> callback)
        {
            WebClient WebClient = new WebClient();
            WebClient.Encoding = Encoding.UTF8;

            GetJSON(WebClient, url, callback);
        }

        public static void GetJSON(WebClient WebClient, string url, Action<string> callback)
        {
            WebClient.DownloadStringCompleted += (s, e) => callback(e.Result);
            WebClient.DownloadStringAsync(new Uri(url, UriKind.Absolute));
        }

        //JSON serialization - http://www.joe-stevens.com/2009/12/29/json-serialization-using-the-datacontractjsonserializer-and-c/
        public static void FromJSON<T>(string url, Action<T> callback) where T : class
        {
            WebClient WebClient = new WebClient();
            WebClient.Encoding = Encoding.UTF8;

            FromJSON(WebClient, url, callback);
        }


        public static void FromJSON<T>(WebClient WebClient, string url, Action<T> callback) where T : class
        {
            GetJSON(WebClient, url, cb =>
                {
                    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(cb)))
                    {
                        DataContractJsonSerializer DataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
                        callback(DataContractJsonSerializer.ReadObject(stream) as T);
                    }
                });
        }
#endif
    }
}
